package com.woniuxy.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

import static com.woniuxy.untis.Sleep.sleep;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 固定大小线程池
 * <P> Date: 2022/4/10:16:31
 * <P> Description:
 */
@Slf4j(topic = "c.ThreadPoolTest04")
@SuppressWarnings("all")
public class ThreadPoolTest04 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(1);


    }

    private static void invokeAny(ExecutorService pool) throws InterruptedException, ExecutionException {
        String result = pool.invokeAny(Arrays.asList(
                () -> {
                    log.debug("begin");
                    Thread.sleep(1000);
                    log.debug("end");
                    return "1";
                },

                () -> {
                    log.debug("begin");
                    Thread.sleep(2000);
                    log.debug("end");
                    return "2";
                },

                () -> {
                    log.debug("begin");
                    Thread.sleep(1000);
                    log.debug("end");
                    return "3";
                }
        ));

        log.debug(result);
    }

    private static void invokeAll(ExecutorService pool) throws InterruptedException {
        List<Future<String>> futures = pool.invokeAll(Arrays.asList(
                () -> {
                    log.debug("begin");
                    Thread.sleep(1000);
                    log.debug("end");
                    return "1";
                },

                () -> {
                    log.debug("begin");
                    Thread.sleep(2000);
                    log.debug("end");
                    return "2";
                },

                () -> {
                    log.debug("begin");
                    Thread.sleep(1000);
                    log.debug("end");
                    return "3";
                }
        ));
        futures.forEach(future -> {
            try {
                log.debug(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }


    public static void submit(ExecutorService pool) throws ExecutionException, InterruptedException {
        Future<String> future = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.debug("running");
                Thread.sleep(1000);
                return "ok";
            }
        });

        // 阻塞 等待结果
        log.debug(future.get());
    }
}
